<template>
  <el-upload
    class="upload-demo"
    action="http://localhost:8081/api/image/upload/"
    :headers="headers"
    name="picture"
    :before-upload="beforeAvatarUpload"
    :on-success="handleSuccess"
    :on-remove="handleRemove"
    :before-remove="beforeRemove"
    :limit="limitMax"
    :file-list="photoList"
    list-type="picture">
    <el-button size="small" :disabled="disabled">点击上传</el-button>
  </el-upload>
</template>

<script>
export default {
  name: "AddImage",
  data() {
    return {
      headers: {
        token: window.localStorage['token']
      },
      photoList: [],
      limitMax: 1,
      disabled: false,
      photoName: ''
    }
  },
  methods: {
    handleSuccess(file) {
      // 如果上传成功
      if (file.success) {
        this.disabled = true
        this.$message.success("图片添加成功")
        this.$emit("getfile", file)
        this.photoName = file.message
      }
    },
    /*
    * 上传前判断文件类型
    * */
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 10MB!');
      }
      return isJPG && isLt2M;
    },
    /*
    * 确认删除时调用该方法
    * */
    handleRemove() {
      this.$axios.post("/image/delete", {'name': this.photoName}).then(result => {
        if (result.data.code === 200) {
          this.$message.success(result.data.result)
        }
        this.disabled = false
        this.photoList = []
        console.log(this.photoList)
      })
    },
    /*
    * 在删除前确认
    * */
    beforeRemove(file) {
      let a = true;
      if (file && file.status === "success") {
        a = this.$confirm(`确定移除 ${file.name}？`);
      }
      return a;
    },
    clean(){
      this.photoList = []
      this.disabled = false
      this.photoName = ''
    }
  }
}
</script>

<style scoped>

</style>
